package com.jh.tools.base;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;

import com.jh.tools.base.util.TUtil;
import com.jh.tools.common.AppManager;

/**
 * Created by niejiahuan on 2016/5/31.
 * 父类activity
 */
public abstract class BaseActivity<T extends BasePresenter,E extends BaseModel>  extends AppCompatActivity {
    public T mPresenter;//UI控制层
    public E mModel;//数据操作层
    public long mExitTime;
    public boolean isNeedConfirmAppExit=false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (this.getLayoutId()!=0){
            this.setContentView(this.getLayoutId());
            AppManager.getAppManager().addActivity(this);
            mPresenter = TUtil.getT(this, 0);
            mModel = TUtil.getT(this, 1);
            this.initPresenter();
            this.initView();

        }else{
            throw new RuntimeException(
                    "Class need add LayoutId");
        }
    }

    public void setNeedConfirmAppExit(boolean needConfirmAppExit) {
        isNeedConfirmAppExit = needConfirmAppExit;
    }

    /**
     * 获取布局文件
     * @return
     */
    public abstract int getLayoutId();

    /**
     * 初始化视图操作
     */
    public abstract void initView();

    /**
     * 简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
     */
    public abstract void initPresenter();
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (isNeedConfirmAppExit){
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this,"再按一次退出",Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
                return false;
            } else {
                AppManager.getAppManager().AppExit(this);
                return true;
            }
        }}
        return super.dispatchKeyEvent(event);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // TODO Auto-generated method stub
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onDestroy() {
        if (null!=mPresenter){
            mPresenter.onDestroy();
        }
        AppManager.getAppManager().finishActivity(this);
        super.onDestroy();
    }
}
